class LifeSquare {
    constructor() {
        this.lifeList = [];
        this.page = 1;
        this.loading = false;
        this.hasMore = true;
        this.container = document.querySelector('.life-list');
        this.loadingEl = document.querySelector('.loading-more');
        
        this.initializeEventListeners();
        this.loadLifeList();
    }

    initializeEventListeners() {
        // 监听滚动到底部
        window.addEventListener('scroll', () => {
            if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100) {
                this.loadMore();
            }
        });

        // 监听购买按钮点击
        this.container.addEventListener('click', (e) => {
            if (e.target.classList.contains('buy-btn')) {
                e.stopPropagation();
                const card = e.target.closest('.life-card');
                const id = card.dataset.id;
                this.handleBuy(id);
            }
        });
    }

    async loadLifeList() {
        if (this.loading || !this.hasMore) return;
        
        this.loading = true;
        this.loadingEl.style.display = 'block';
        
        try {
            // 模拟API调用
            const newList = await this.mockGetLifeList();
            this.lifeList = [...this.lifeList, ...newList];
            this.page++;
            this.hasMore = newList.length === 10;
            
            this.renderLifeList(newList);
        } catch (error) {
            console.error('加载生命列表失败:', error);
            alert('加载失败，请稍后重试');
        } finally {
            this.loading = false;
            this.loadingEl.style.display = 'none';
        }
    }

    mockGetLifeList() {
        return new Promise((resolve) => {
            setTimeout(() => {
                const list = Array(10).fill(0).map((_, index) => ({
                    id: (this.page - 1) * 10 + index + 1,
                    name: `意识体 ${(this.page - 1) * 10 + index + 1}`,
                    avatar: '/images/default-avatar.png',
                    description: '这是一个充满智慧和创造力的数字生命体',
                    price: Math.floor(Math.random() * 1000) + 100,
                    tags: ['幽默', '智慧', '创造力']
                }));
                resolve(list);
            }, 1000);
        });
    }

    renderLifeList(list) {
        const html = list.map(life => `
            <div class="life-card" data-id="${life.id}">
                <img class="avatar" src="${life.avatar}" alt="${life.name}">
                <h3 class="name">${life.name}</h3>
                <p class="description">${life.description}</p>
                <div class="tags">
                    ${life.tags.map(tag => `<span class="tag">${tag}</span>`).join('')}
                </div>
                <div class="price">¥${life.price}</div>
                <button class="buy-btn">购买</button>
            </div>
        `).join('');
        
        this.container.insertAdjacentHTML('beforeend', html);
    }

    loadMore() {
        this.loadLifeList();
    }

    handleBuy(id) {
        const life = this.lifeList.find(item => item.id === parseInt(id));
        if (!life) return;

        if (confirm(`确定要购买 ${life.name} 吗？价格：¥${life.price}`)) {
            this.processPayment(life);
        }
    }

    processPayment(life) {
        // 模拟支付过程
        alert('正在处理支付...');
        setTimeout(() => {
            alert('购买成功！');
        }, 2000);
    }
}

// 创建生命广场实例
window.lifeSquare = new LifeSquare(); 